//var width = document.documentElement.clientWidth;
//var height = document.documentElement.clientHeight;

//function getRandom(min, max) {
//	var r = Math.random() * (max - min);
//	var re = Math.round(r + min);
//	re = Math.max(Math.min(re, max), min)
//	return re;
//}


var DEBUG = true; //本地测试

//默认当前手机是竖向
var orientation_portrait_flag = true;
//是否微信端
var is_wx = false;
var ua = navigator.userAgent.toLowerCase();
//在微信中打开
if (ua.match(/MicroMessenger/i) == "micromessenger") {
    is_wx = true;
}

$(function () {

    //适配
    var width = $(window).width();
    var height = $(window).height();

    var largebox = $('#largebox');
    var fontSize = 100, //100为根元素字体大小
        pageW = 667, //设计稿页面宽度
        pageH = 375; //设计稿页面高度

    //竖屏
    if (width < height) {
        largebox.width(height);
        largebox.height(width);
        largebox.css('top', (height - width) / 2);
        largebox.css('left', 0 - (height - width) / 2);
        largebox.css('transform', 'rotate(90deg)');
        largebox.css('-webkit-transform', 'rotate(90deg)');
        largebox.css('transform-origin', '50% 50%');
        largebox.css('-webkit-transform-origin', '50% 50%');

        $("html").css('font-size', height / pageW * fontSize + "px");

        set_overlay_scroll('portrait');

    } else {
        largebox.width(width);
        if (is_wx) {
            largebox.width(width - 50); //加上头部大致高度
        } else {
            largebox.width(width);
        }
        largebox.height(height);
        //横竖根字体大小保持一致
        if (is_wx) {
            $("html").css('font-size', (width - 50) / pageW * fontSize + "px");
        } else {
            $("html").css('font-size', (width) / pageW * fontSize + "px");
        }

        set_overlay_scroll('landscape');
        orientation_portrait_flag = false;
    }

    var screen_width = window.screen.availWidth; //屏幕宽度 固定不变
    var screen_height = window.screen.availHeight; //屏幕宽度 固定不变

    var evt = "onorientationchange" in window ? "orientationchange" : "resize";
    window.addEventListener(evt, function () {
        var O_width = $(window).width(); //文档宽度
        var O_height = $(window).height(); //文档高度
        //		var inner_height = window.innerHeight;
        //		alert(O_width + ';' + O_height +';');
        if (O_width > O_height) {

            if (is_wx) {
                //竖向
                if (O_width == screen_width) {
                    //微信竖屏时获得的O_width是屏幕宽度；o_height是横向文档高度
                    largebox.width(Math.max(width, height));
                    largebox.height(screen_width);
                    largebox.css('top', (height - screen_width) / 2);
                    largebox.css('left', 0 - (height - screen_width) / 2);
                    largebox.css('transform', 'rotate(90deg)');
                    largebox.css('-webkit-transform', 'rotate(90deg)');
                    largebox.css('transform-origin', '50% 50%');
                    largebox.css('-webkit-transform-origin', '50% 50%');

                    $("html").css('font-size', O_height / pageH * fontSize + "px");
                    //绑定浮层主内容的滑动
                    set_overlay_scroll('portrait');
                    orientation_portrait_flag = true;
                }
                //横向
                else if (O_width == screen_height) {
                    //微信横屏时获得的width是屏幕高度；height是竖向时的文档高度
                    largebox.width(screen_height);
                    largebox.height(Math.min(width, height) - 50); //减去头部大致高度..
                    largebox.css('top', 0);
                    largebox.css('left', 0);
                    largebox.css('transform', 'none');
                    largebox.css('-webkit-transform', 'none');
                    largebox.css('transform-origin', '50% 50%');
                    largebox.css('-webkit-transform-origin', '50% 50%');
                    $("html").css('font-size', (Math.min(width, height) - 50) / pageH * fontSize + "px");

                    set_overlay_scroll('landscape');
                    orientation_portrait_flag = false;
                }
            } else {
                //other 横
                largebox.width(O_width);
                largebox.height(O_height);
                largebox.css('top', 0);
                largebox.css('left', 0);
                largebox.css('transform', 'none');
                largebox.css('-webkit-transform', 'none');
                largebox.css('transform-origin', '50% 50%');
                largebox.css('-webkit-transform-origin', '50% 50%');
                $("html").css('font-size', O_width / pageW * fontSize + "px");

                set_overlay_scroll('landscape');
                orientation_portrait_flag = false;
            }

        } else {
            //other 竖
            largebox.width(O_height);
            largebox.height(O_width);
            largebox.css('top', (O_height - O_width) / 2);
            largebox.css('left', 0 - (O_height - O_width) / 2);
            largebox.css('transform', 'rotate(90deg)');
            largebox.css('-webkit-transform', 'rotate(90deg)');
            largebox.css('transform-origin', '50% 50%');
            largebox.css('-webkit-transform-origin', '50% 50%');
            $("html").css('font-size', O_height / pageW * fontSize + "px");

            set_overlay_scroll('portrait');
            orientation_portrait_flag = true;
        }

        //每次旋转时需要做的恢复
        $(".two_star_overlay").find('overlay_main_content').attr('style', '');
    }, false);


    //浮层
    $('.cancel').on("click", function () {
        $(this).parent().hide();
    });
    $('.draw_record_btn').on("click", function () {
        audioAutoPlay('click_btn_music');
        getBetLog();
        $(".draw_record_overlay").show();
    });
    $('.reward_record_btn').on("click", function () {
        audioAutoPlay('click_btn_music');
        getLotteryLog();
        $(".reward_record_overlay").show();
    });
    $('.two_words_btn').on("click", function () {
        audioAutoPlay('click_btn_music');
        $(".two_star_overlay").show().find('overlay_main_content').attr('style', '');
    });
    $('.explain_btn').on("click", function () {
        audioAutoPlay('click_btn_music');
        $(".how_to_play").show().find('overlay_main_content').attr('style', '');
    });
    click_btn_action($('.draw_record_btn'));
    click_btn_action($('.reward_record_btn'));
    click_btn_action($('.two_words_btn'));
    click_btn_action($('.explain_btn'));

    //点击左右两边头像
    $(document).on("click", '.partner_avatar_section', function () {
        if (!$(this).data('user')) {
            if (!IS_ENTER) {
                enter_room();
                return false;
            }
        }

        //判断时间
        // if ($('.time_box').html() <= 10) {
        //     set_alert('tip', '倒计时10s内不能投注');
        //     return false;
        // }
        //先把投币交互做在这里
        // var that = $(this);
        // //头像的位置和金币类型
        // //竖向
        // if (orientation_portrait_flag) {
        //     var ori_x = that.offset().top;
        //     var ori_y = that.offset().left + (that.height() * 0.5);
        // } else {
        //     var ori_x = that.offset().left;
        //     var ori_y = that.offset().top;
        // }
        // var coin_type = 3;
        // var gold_area_arr = ['big', 'single'];
        // //处理投掷数据并丢币
        // deal_draw_data(gold_area_arr, ori_x, ori_y, coin_type);
    });
    set_ratio();
})

//背景音乐 
function audioAutoPlay(id) {
    var audio = document.getElementById(id);
    audio.play();
    document.addEventListener("WeixinJSBridgeReady", function () {
        audio.play();
    }, false);
}

//使悬浮层内容可滚动
function set_overlay_scroll(orientation) {
    //先移除绑定事件
    remove_overlay_scroll();

    var last_top = 0; //上次div移动的位置
    var last_move_x; //上次手指触摸的位置
    $('.overlay_main').on("touchstart", function (e) {

        var that = $(this);
        var overlay_main_height = that.height();
        var overlay_main_content = that.find('.overlay_main_content');
        var overlay_main_content_height = overlay_main_content.height();

        var max_scroll_height = overlay_main_content_height - overlay_main_height;

        //如果需要滚动
        if (max_scroll_height <= 0) {
            return false;
        }
        var init_touch = e.originalEvent.targetTouches[0];

        //竖向
        if (orientation == 'portrait') {

            var init_x = init_touch.pageX;
        }
        //横向
        else if (orientation == 'landscape') {
            var init_x = init_touch.pageY;
        }

        var trans = 0;
        last_move_x = init_x;
        var _top; //div位移

        that.on("touchmove", function (e) {
            var move_touch = e.originalEvent.targetTouches[0];
            //竖向
            if (orientation == 'portrait') {
                var move_x = move_touch.pageX;
                trans = move_x - last_move_x;
            }
            //横向
            else if (orientation == 'landscape') {
                var move_x = move_touch.pageY;
                trans = last_move_x - move_x;
            }

            _top = last_top - trans;

            if (_top > 0) {
                _top = 0;
            } else if (-_top > max_scroll_height) {
                _top = -max_scroll_height;
            }
            if (orientation_portrait_flag) {
                overlay_main_content.css('transform', 'translateY(' + _top + 'px)');
                overlay_main_content.css('-webkit-transform', 'translateY(' + _top + 'px)');
            } else {
                overlay_main_content.animate({
                    'scrolltop': -_top + 'px'
                });
            }

            last_move_x = move_x;
            last_top = _top;

        });

        //		e.stopPropagation();
        //		e.preventDefault();
    })
}

//移除滚动
function remove_overlay_scroll() {
    $('.overlay_main').attr('style', '').off();
}


//数字转动
function reset_number(data, step) {
    if (!data) {
        return false;
    }
    seconds = 9;
    set_alert('tip', '正在开奖……', 10 * 1000)
    // $.post(GV.url + 'Game/getCurrentLotteryNumber', post_data,function (data) {
    //     if (data.ResponseStatus == 0) {
    var code = data;
    var lottery_div = $('.lottery_div');
    lottery_div.each(function () {

        //需要每次生成一个间隔时间
        var that = $(this);
        var cur_time = 0;
        var total_time = 2000;
        var step = 100;
        var set_reward_number = function () {
            var reward_number_timer = setTimeout(function () {
                var cur_span = that.find('span').eq(0);
                cur_time += step;

                var num = (function () {
                    return getRandom(0, 9);
                })
                lottery_div.find('span').html(num);
                if (cur_time >= total_time) {
                    clearTimeout(reward_number_timer);
                    reward_number_timer = null;
                } else {
                    set_reward_number();
                }
            }, step);
        }
        set_reward_number();

        //显示到左上框框中 todo

    });
    setTimeout(function () {
        lottery_div.each(function (i, n) {
            $(this).html(code[i]);
        });

        lottery_num = {};

    }, 2000)


}


function clearLotteryNumber() {
    var lottery_div = $('.lottery_div');
    lottery_div.each(function (i, n) {
        $(this).html('0');

    });

}

function setLotteryNumber(data) {
    var lottery_div = $('.lottery_div');
    lottery_div.each(function (i, n) {
        $(this).html(data[i]);

    });

}

// 获取随机数 避免没有最小值或最大值
function getRandom(minNumber, maxNumber) {
    var randomResult = 0;
    var firstRandom = Math.random();
    var secondRandom = Math.random();
    randomResult = minNumber + Math.floor(firstRandom * (maxNumber - minNumber)) + ((firstRandom + secondRandom) >= 1 ? 1 : 0);

    return randomResult;
}

//提示
var alert_timer = null;

function set_alert(type, content, time, notime) {
    notime = notime ? notime : false;
    if (type == 'tip') {
        var dom = $('.tip_box');
        dom.html(content);
        dom.fadeIn(150);
    } else if (type == 'start_draw') {
        var dom = $('.start_draw');
        dom.show();
    } else if (type == 'stop_draw') {
        var dom = $('.stop_draw');
        dom.show();
    } else {
        return false;
    }
    if (!notime) {
        if (alert_timer != null) {
            clearTimeout(alert_timer);
        }
        alert_timer = setTimeout(function () {
            dom.hide();
            clearTimeout(alert_timer);
        }, time ? time : 2000);
    }
}

function set_mask(){
    $('#mask').show();
}

//点击按钮变大变小的效果
function click_btn_action(obj) {
    obj.on('touchstart', function () {
        obj.css('transform', 'scale(0.9)');
        obj.css('-webkit-transform', 'scale(0.9)');
    }).on('touchend', function () {
        obj.css('transform', 'scale(1)');
        obj.css('-webkit-transform', 'scale(1)');
    })
}


//请求赔率
function set_ratio() {

    $.ajax({
        url: GV.url + 'Game/getRate',
        async: false,
        type: "POST",
        data: {token: token},
        dataType: "json",
        success: function (data) {
            if (data.ResponseStatus == 0) {
                var rate = data.datas;
                $('[data-area="big"]').find('.odds').html('1:' + rate.da_rate)
                $('[data-area="small"]').find('.odds').html('1:' + rate.xiao_rate)
                $('[data-area="single"]').find('.odds').html('1:' + rate.dan_rate);
                $('[data-area="double"]').find('.odds').html('1:' + rate.shuang_rate)
                // coonsole.log(data.datas)
            }
        }
    });

}